package batch.execution;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;

public class AbstractVO {
	private String batchDescription;
	private String batchCfgName;
	
	public String getBatchDescription() {
		return batchDescription;
	}

	public void setBatchDescription(String batchDescription) {
		this.batchDescription = batchDescription;
	}

	public String getBatchCfgName() {
		return batchCfgName;
	}

	public void setBatchCfgName(String batchCfgName) {
		this.batchCfgName = batchCfgName;
	}

	public Map<String,Object> toMap() {
		Field[] fields = this.getClass().getDeclaredFields();
		Map<String,Object> map = new HashMap<String,Object>();
		for (Field field : fields) {
			String fieldName = field.getName();
			Object value = callGetMethodFor(fieldName);
			map.put(fieldName, value);
		}
		return map;
	}

	public void fromMap(Map<String,Object> map) {
		Field[] fields = this.getClass().getDeclaredFields();
		for (Field field : fields) {
			String fieldName = field.getName();
			Object value = MapUtils.getObject(map, fieldName);
			if( value != null ) {
				callSetMethodFor(fieldName, value);
			}
		}
	}

	private void callSetMethodFor(String key, Object value) {
		try {
			this.getClass().getMethod(setterMethodNameBy(key), value.getClass()).invoke(this, value);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private Object callGetMethodFor(String fieldName) {
		try {
			return this.getClass().getMethod(getterMethodNameBy(fieldName)).invoke(this);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}


	private String getterMethodNameBy(String fieldName) {
		return "get" + StringUtils.capitalize(fieldName);
	}
	private String setterMethodNameBy(String fieldName) {
		return "set" + StringUtils.capitalize(fieldName);
	}
}
